<?php
/**
 * SweetPlurk
 *
 * @package    SweetPlurk
 * @copyright  Copyright (c) 2008-2012 Wabow Information Inc. (http://www.wabow.com)
 * @license    New BSD License
 * @version    $Id$
 */

/**
 * Connector 類別
 *
 * @package    SweetPlurk
 * @copyright  Copyright (c) 2008-2012 Wabow Information Inc. (http://www.wabow.com)
 * @license    New BSD License
 */
abstract class SweetPlurk_Connector
{
    /**
     * connect hanlder
     *
     * @var resource
     */
    protected $_handler = null;

    /**
     * API Key
     *
     * @var string
     */
    protected $_options = array(
        'apiKey' => '',
        'apiUrl' => 'http://www.plurk.com/API',
        'cookiePath' => 'cookie.txt',
    );

    /**
     * API Url
     *
     * @var string
     */
    protected $_apiUrl = null;

    /**
     * 建構子
     *
     */
    public function __construct($options)
    {
        $this->_setOptions($options);
        $this->_init();
    }

    /**
     * 物件銷毀
     *
     */
    public function __destruct()
    {
        $this->close();
    }

    /**
     * 處理設定
     *
     * @param array $options
     */
    protected function _setOptions($options)
    {
        $options = (array) $options;
        foreach (array_keys($this->_options) as $key) {
            if (array_key_exists($key, $options)) {
                $this->_options[$key] = $options[$key];
            }
        }
    }

    /**
     * 初始化 HTTP 連線資源
     *
     */
    protected function _init()
    {
    }

    /**
     * 傳送 POST 資訊
     *
     * @param string $url
     * @param array $data
     * @return string
     */
    protected function _post($url, $data)
    {
        return '';
    }

    /**
     * 關閉資源
     *
     */
    protected function _close()
    {
    }

    /**
     * 設定 Cookie
     *
     */
    protected function _setCookie()
    {
    }

    /**
     * 重設 Cookie
     *
     */
    public function resetCookie()
    {
        @unlink($this->_options['cookiePath']);
        $this->_setCookie();
    }

    /**
     * 關閉連線
     *
     */
    public function close()
    {
        $this->_close();
    }

    /**
     * 傳送資訊
     *
     * @param string $url
     * @param array $data
     * @return array
     */
    public function send($function, $data)
    {
        $error = false;
        $data = (array) $data;
        if (!preg_match('/\/\w+\/\w+[\w\/]*/i', $function)) {
            $error = true;
            $result = (object) array('error_text' => 'Invalid API');
        }

        if (!$error) {
            $data['api_key'] = $this->_options['apiKey'];
            $result = $this->_post($this->_options['apiUrl'] . $function, $data);
            if (false !== strpos($result, '<!DOCTYPE', 0)) {
                $result = (object) array('error_text' => 'Invalid API');
            } else {
                $result = (object) json_decode($result);
            }
        }
        return $result;
    }
}